package com.hengpeng.itfin.service.impl;

import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.hengpeng.common.exception.ServiceResult;
import com.hengpeng.common.persist.entity.AbstractEntity.BoolValue;
import com.hengpeng.common.persist.query.DynamicQuery;
import com.hengpeng.common.util.StringHelper;
import com.hengpeng.common.util.Validate;
import com.hengpeng.itfin.common.Configuration;
import com.hengpeng.itfin.common.MessageUtil;
import com.hengpeng.itfin.common.SystemConfigUtil;
import com.hengpeng.itfin.service.ServiceFactory;
import com.hengpeng.itfin.service.SmsService;
import com.hengpeng.itfin.sms.SmsSendFactory;
import com.hengpeng.itfin.tools.TemplateUtil;
import com.hengpeng.itfinbase.constants.RespCodeConstants;
import com.hengpeng.itfinbase.message.ResponseMessage;
import com.hengpeng.itfinbase.message.admin.SmsResendRequest;
import com.hengpeng.itfinbase.message.userInfo.SendSMSRequest;
import com.hengpeng.itfinbase.message.userInfo.UserInfoResponse;
import com.hengpeng.itfinbase.persist.SmsLog.SmsLogTransType;
import com.hengpeng.itfinbase.persist.SmsPartner;
import com.hengpeng.itfinbase.persist.UserInfo;
import com.hengpeng.itfinbase.persist.UserInfo.UserInfoStatus;
import com.hengpeng.itfinbase.persist.VerifyCode;
import com.hengpeng.itfinbase.persist.VerifyCode.VerifyType;

/**
 * <pre>
 *短信服务类
 * </pre>
 * @author shanguogang
 * @version 1.0, 2015-7-31
 */
@Transactional
@Service
@Lazy
public class SmsServiceImpl extends BaseServiceImpl implements SmsService, ApplicationContextAware
{

	@Override
	public void setApplicationContext(ApplicationContext context) throws BeansException
	{
		// 初始化所有正常开通的短信网关
		ServiceFactory bean = context.getBean(ServiceFactory.class);

		DynamicQuery query = new DynamicQuery(SmsPartner.class);
		query.eq("status", SmsPartner.SmsPartnerStatus.OPEN);
		List<SmsPartner> list = bean.getPersistService().findByDynamicQuery(SmsPartner.class, query);
		for (SmsPartner partner : list)
		{
			try
			{
				SmsSendFactory.clearGateway(partner.getId());
				SmsSendFactory.getGateway(context, partner);
			}
			catch (Exception e)
			{
				logger.error("初始化短信网关异常", e);
			}
		}
	}

	@Override
	public ResponseMessage confirmValidSMS(SendSMSRequest request)
	{
		ResponseMessage response=new ResponseMessage();
		// 参数空值效验
		if (Validate.validateObjectsNullOrEmpty(request.getMobile(), request.getVerifyCode()))
		{
			return MessageUtil.getErrorResponseMessage(UserInfoResponse.class,RespCodeConstants.CommonCode.DATA_NOT_VALIDATA,
			"参数错误");
		}
		VerifyCode bean=null;
		UserInfo user=null;
		if (VerifyCode.VerifyType.REGISTER==request.getType() || VerifyCode.VerifyType.FOUNDLOGINPWD == request.getType())
		{
			bean= serviceFactory.getPersistService().getByNamedQuery(VerifyCode.class,
					"verifyCode.getByMobileAndValueAndType",
					new Object[] {request.getMobile(), request.getVerifyCode(), request.getType()});
		}else{
			user=serviceFactory.getUserInfoService().getUserByUserName(request.getUsername());
			if (user == null)
			{
				return MessageUtil.getErrorResponseMessage(ResponseMessage.class,RespCodeConstants.MemberCode.ACCOUNT_NOT_FOUND,
				"用户不存在");
			}
			// 检查用户状态是否正常
			if (user.getStatus() != UserInfoStatus.NORMAL)
			{
				return MessageUtil.getErrorResponseMessage(ResponseMessage.class,RespCodeConstants.MemberCode.MEMBER_STATUS_EXCEPTION,
				"用户状态不正确");
			}
			bean= serviceFactory.getPersistService().getByNamedQuery(VerifyCode.class,
					"verifyCode.getByUserNameAndValueAndType",
					new Object[] {user.getUserName(), request.getVerifyCode(), request.getType()});
		}
		// 万能验证码
		String wanneng = Configuration.getValue("sms.validate.code");
		// 后门短信验证码验证
		if (wanneng.equals(request.getVerifyCode()))
		{
			return response;
		}
		if (bean == null)
		{
			// 非法链接
			return MessageUtil.getErrorResponseMessage(ResponseMessage.class,RespCodeConstants.MemberCode.MEMBER_CHECKCODE_FAILED,
			"验证码错");
		}
		if (bean.getValid().equals(BoolValue.YES))
		{
			if (bean.getPastDate().before(new Date()))
			{// 过期
				bean.setValid(BoolValue.NO);
				serviceFactory.getPersistService().update(bean);
				return MessageUtil.getErrorResponseMessage(ResponseMessage.class,RespCodeConstants.MemberCode.RESET_PASS_URL_INVALIDATION,
				"已经过期");
			}
			else
			{// 有效
				bean.setValid(BoolValue.NO);
				serviceFactory.getPersistService().update(bean);
				return response;
			}
		}
		else
		{// 效检码失效
			return MessageUtil.getErrorResponseMessage(ResponseMessage.class,RespCodeConstants.MemberCode.MEMBER_FIND_PASS_AFFIRM_CODE_INVALID,
			"验证码失效");
		}
	}

	@Override
	public ServiceResult<Boolean> resendSMS(SmsResendRequest request)
	{
		return null;
	}

	@Override
	public ResponseMessage sendValidSMS(SendSMSRequest request)
	{
		ResponseMessage result = new ResponseMessage();
		try
		{
			
			Long smsProviderId = null;
			Long userProviderId = request.getSmsProviderId();
			String systemProviderId = Configuration.getValue("sms.verifycode.providerid");
			if (userProviderId != null)
			{// 直接指定的短信编号
				smsProviderId = userProviderId;
			}
			else if (!StringHelper.isEmpty(systemProviderId))
			{// 系统配置的短信编号
				smsProviderId = Long.valueOf(systemProviderId);
			}
			else
			{
				logger.error("短信验证码发送通道[sms.verifycode.providerid]参数配置错误");
				return MessageUtil.getErrorResponseMessage(ResponseMessage.class,RespCodeConstants.CommonCode.TRANS_FAIL,
				"短信通道配置错误");
			}
			Calendar paseDate = Calendar.getInstance();
			if (request.getPastSeconds() != null)
			{
				paseDate.add(Calendar.SECOND, request.getPastSeconds());
			}
			else
			{
				paseDate.add(Calendar.MINUTE, 10);
			}
			VerifyCode verifyCode = serviceFactory.getDaoFactory().getVerifyCodeDao()
					.createForSMS(request.getUsername(), request.getType(), paseDate.getTime(), request.getMobile());
			String content = "";
			//网站名
			String webName=SystemConfigUtil.getConfigValue("webName");
			if (StringHelper.isEmpty(request.getContent()))
			{
				if (VerifyCode.VerifyType.FOUNDLOGINPWD.name().equals(request.getType().name()))
				{
					content = TemplateUtil.makeSMSTemplateContent(verifyCode.getValue(), webName, "",
							"findLoginPasswordSMS.ftl");
				}
				else if (VerifyCode.VerifyType.FOUNDACCOUNTPWD.name().equals(request.getType().name()))
				{
					content = TemplateUtil.makeSMSTemplateContent(verifyCode.getValue(), webName, "",
							"findPayPasswordSMS.ftl");
				}
				else if (VerifyCode.VerifyType.VALIDMOBILE.name().equals(request.getType().name()))
				{
					content = TemplateUtil.makeSMSTemplateContent(verifyCode.getValue(), webName, "",
							"validSMS.ftl");
				}
				else if (VerifyCode.VerifyType.REGISTER.name().equals(request.getType().name()))
				{
					content = TemplateUtil.makeSMSTemplateContent(verifyCode.getValue(),webName, "",
							"registerSMS.ftl");
				}
				else
				{
					content = TemplateUtil.makeSMSTemplateContent(verifyCode.getValue(),webName, "",
							"defaultSMS.ftl");
				}
			}
			else
			{
				content = request.getContent();
			}
			serviceFactory.getSmsSendService().sendNow(request.getMobile(), content, Long.valueOf(smsProviderId),
					SmsLogTransType.VALID);
			result.setReturnObject(verifyCode.getValue());
		}
		catch (Exception e)
		{
			return MessageUtil.getErrorResponseMessage(ResponseMessage.class,RespCodeConstants.CommonCode.TRANS_FAIL,
			"发送失败");
		}
		return result;
	}
}
